//
//  BaseImgTableHeader.m
//  KuaiTu
//
//  Created by 江伟 on 2018/10/27.
//  Copyright © 2018年 WeiJiang. All rights reserved.
//

#import "BaseImgTableHeader.h"
@interface BaseImgTableHeader()
@property (nonatomic,strong) UIImageView *bgImg;
@property (assign, nonatomic) CGFloat headerViewHeight;
@property (nonatomic,strong) NSMutableArray *subVTopArray;
@end
@implementation BaseImgTableHeader

CGFloat const kMaxScrollContentSizeY = 280;

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        if (!_bgImg) {
            _bgImg = [[UIImageView alloc] initWithFrame:self.bounds];
            [self addSubview:_bgImg];
            self.frame = frame;
            self.headerViewHeight = frame.size.height;
        }
    }
    return self;
}

- (void)setupViews {
    if (!_bgImg) {
        _bgImg = [[UIImageView alloc] initWithFrame:self.bounds];
        [self addSubview:_bgImg];
    }
}

- (void)addSubview:(UIView *)view {
    if (view != _bgImg && _bgImg != nil) {
        [_bgImg addSubview:view];
        return;
    }
    [super addSubview:view];
}

- (void)setBgImage:(UIImage *)img {
    self.bgImg.image = img;
}

- (void)dragHeaderOffsetY:(CGFloat)offsetY {
    if (!_subVTopArray) {
        _subVTopArray = [NSMutableArray array];
        for (UIView *subV in self.bgImg.subviews) {
            [_subVTopArray addObject:[NSString stringWithFormat:@"%f",subV.frame.origin.y]];
        }
    }
    CGRect frame = self.frame;
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    if (offsetY < 0) {
        frame.size.height = (self.headerViewHeight + ABS(offsetY))>kMaxScrollContentSizeY?kMaxScrollContentSizeY:(self.headerViewHeight + ABS(offsetY));
        frame.origin.y = 0;//及时归零
        
        CGFloat f = (self.headerViewHeight + ABS(offsetY)) / self.headerViewHeight;//缩放比
        //拉伸后的图片的frame应该是同比例缩放。
        frame =  CGRectMake(- (width * f - width) / 2, 0, width * f, (self.headerViewHeight + ABS(offsetY)));
        
        for (UIView *subV in self.bgImg.subviews) {
            subV.top = subV.top + (self.frame.size.height - self.headerViewHeight);
        }
        
    } else {//向上滑
        //取消向上滑到顶的弹簧效果
        UIScrollView *scro = (UIScrollView *)self.superview;
        scro.contentOffset = CGPointZero;
        frame.size.height = self.headerViewHeight;
        frame.origin.y = 0;//-offsetY
        for (int i = 0; i < self.bgImg.subviews.count; i++) {
            UIView *subV = self.bgImg.subviews[i];
            subV.top = [self.subVTopArray[i] floatValue];
        }
    }
    self.frame = frame;
}

- (NSMutableArray *)subVTopArray {
    if (!_subVTopArray) {
        _subVTopArray = [NSMutableArray array];
    }
    return _subVTopArray;
}
@end
